<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="70px"
    style="margin-top: 10px"
  >
    <el-row :gutter="10">
      <el-col :span="24">
        <el-form-item label="类别" prop="examType">
          <el-select
            v-model="form.examType"
            placeholder="请选择类别"
            style="width: 100%"
            @change="examTypeChange"
          >
            <el-option
              v-for="exam in typeList"
              :key="exam.examTypeId"
              :label="exam.name"
              :value="exam.examTypeId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="检查项目" prop="examNameList">
      <div
        v-if="selectedExamList.length > 0"
        class="exam-lab-type-div ml5"
        style="
          word-wrap: break-word;
          width: 10px;
          position: absolute;
          margin-left: 10px;
          top: 10px;
        "
      >
        选择项目
      </div>
      <el-card class="box-style box-item" shadow="never" @click="boxItemClick">
        <div
          v-for="(item, index) in selectedExamList"
          :key="index"
          class="ml5"
          style="border-bottom: 0.5px dashed #ababab"
        >
          <span style="width: 180px">{{ item.itemName }} </span>
          <span class="exam-lab-type-div" style="float: right">
            数量:<el-input
            v-model="item.amount"
            class="ml10 amount-input"
            style="width: 40px; height: 22px"
            @input="amountInput"
            @click.stop.native="inputFocused"
          />
            X {{ item.totalPrice.toFixed(2) }} =
            <span> ￥:{{ (item.totalPrice * item.amount).toFixed(2) }} 元 </span>
          </span>
        </div>
      </el-card>
      <div v-if="selectedExamList.length > 0">
        共记：<span class="font-color1">{{ selectedExamList.length }}</span
      >个项目，总计：<span class="font-color1">{{ selectedExamMoney.toFixed(2) }}</span
      >元
      </div>
    </el-form-item>
    <el-form-item label="症状" prop="symptom">
      <el-input v-model="form.symptom" clearable placeholder="请输入症状"/>
    </el-form-item>
    <el-form-item label="其他诊断" prop="relevantDiag">
      <el-input v-model="form.relevantDiag" clearable placeholder="请输入其他诊断"/>
    </el-form-item>
    <el-form-item label="体征" prop="sign">
      <el-input v-model="form.sign" clearable placeholder="请输入体征"/>
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input v-model="form.remarks" clearable placeholder="请输入备注"/>
    </el-form-item>
    <el-button style="float: right" type="primary" @click="submitForm">开单</el-button>
  </el-form>
  <!-- 添加或修改检查申请主对话框 -->
  <el-dialog
    v-model="open"
    :close-on-click-modal="false"
    :title="title"
    append-to-body
    width="70%"
  >
    <item-select-dialog
      ref="itemSelectDialogRef"
      :exam-type="selectedExamType"
      :org-id="props.orgId"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveExamDialog">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {listExamType} from "@/api/base/examType.ts";
import ItemSelectDialog from "@/views/doctor/exam/itemSelectDialog.vue";
import {insertBoByWholeSet} from "@/api/patient/templateDetail.ts";

const props = defineProps({
  orgId: {
    type: String,
    default: ""
  },
  templateMasterId: {
    type: String,
    default: ""
  }
})

const title = "选择检查项目";
const open = ref(false);
const itemSelectDialogRef = ref();
// 已选择的检查类别
let selectedExamType = "";
// 已选择的检查项目
const selectedExamList = ref<any>([]);
// 已选择总计金额
const selectedExamMoney = ref<number>(0.0);
const emits = defineEmits(["submitFormOk"]);
const formRef = ref();
// 检查类别数组
const typeList = ref<any>();
const form = ref<any>({
  isUrgent: "N",
  detailBoList: [],
  orgId: props.orgId,
  type: '3',
  templateMasterId: props.templateMasterId,
});
const rules = ref<any>({
  examType: [{required: true, message: "类别不能为空", trigger: "change"}],
  isUrgent: [{required: true, message: "是否加急不能为空", trigger: "change"}],
});


/** 检查项目卡片点击事件 */
function boxItemClick() {
  if (!selectedExamType) {
    return ElMessage.warning("请选择检查类别");
  }
  open.value = true;
  nextTick(() => {
    itemSelectDialogRef.value.getListExamTypeFun().then(() => {
      // getListExamTypeFun 执行完成后，执行 setListByForm 方法
      itemSelectDialogRef.value.setListByForm(selectedExamList.value);
    })
  })
}

/** 检查类别选择事件 */
function examTypeChange(value) {
  selectedExamType = value;
  const index = typeList.value.findIndex((item) => item.examTypeId === value);
  if (index > -1) {
    // 设置检查类型名称
    form.value.examTypeName = typeList.value[index].remarks
  }
  boxItemClick();
  selectedExamList.value = [];
  selectedExamMoney.value = 0.0;
}

function inputFocused(event) {
  // 阻止冒泡事件
  event.stopPropagation();
}

function amountInput() {
  selectedExamMoney.value = 0.0;
  form.value.detailBoList.forEach((item: any) => {
    selectedExamMoney.value += item.totalPrice * item.amount;
  });
}

function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("确认要保存开单吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 将item对象中的id等信息置空，原因获取字典对象时有原始数据
          form.value.detailBoList.forEach((item: any) => {
            item.num = item.amount;
            item.sumPrice = item.num * item.price;
            item.createBy = "";
            item.createTime = "";
            item.updateBy = "";
            item.updateTime = "";
          });
          insertBoByWholeSet(form.value).then((res: any) => {
            emits("submitFormOk");
            if (res.code === 200) {
              ElMessage.success("开单成功");
              selectedExamList.value = [];
              selectedExamMoney.value = 0.0;
              itemSelectDialogRef.value.emptySearchInput();
              itemSelectDialogRef.value.emptyExamTypeList();
              form.value = {
                detailBoList: [],
                orgId: props.orgId,
                relevantDiag: "",
                remarks: "",
                sign: "",
                symptom: "",
                examType: "",
              };
            } else {
              ElMessage.error("系统接口请求超时");
            }
          });
        })
        .catch(() => {
          ElMessage.info("取消操作");
        });
    }
  });
}

function cancel() {
  open.value = false;
}

function clearForm() {
  form.value.examType = ""
  form.value.detailBoList = []
  form.value.orgId = props.orgId
  form.value.relevantDiag = ""
  form.value.remarks = ""
  form.value.sign = ""
  form.value.symptom = ""
  form.value.examType = ""
  selectedExamList.value = []
}

/** 检查项目选择保存事件 */
function saveExamDialog() {
  const examClinicCheckObjList = itemSelectDialogRef.value.saveExamDialog();
  if (examClinicCheckObjList.length !== 0) {
    selectedExamList.value = examClinicCheckObjList;
    open.value = false;
    form.value.detailBoList = selectedExamList.value;
    // 计算已开项目总金额，用于页面显示
    form.value.detailBoList.forEach((item: any) => {
      // 将默认开单数量修改为 选择的部位数量
      item.amount = item.examPositionArray.length
      selectedExamMoney.value += item.totalPrice * item.amount;
    });
  }
}


getList();

/** 查询检查项目类型exam_type列表 */
function getList() {
  const param = {
    orgId: props.orgId,
    level: "1",
  };
  listExamType(param).then((response: any) => {
    typeList.value = response.data;
  });
}

defineExpose({clearForm})
</script>


<style scoped>
.box-style {
  width: 100%;
}

:deep(.box-style .el-card__body) {
  height: 80px;
  background-color: #f6f6f6;
}

:deep(.box-item .el-card__body) {
  height: 110px !important;
  background-color: #f6f6f6;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: 0 !important;
}

:deep(.amount-input .el-input__wrapper) {
  padding: 0px 1px;
}
</style>
